package com.wish.bio;

import static com.wish.common.MyUtils.getAnswer;

import java.io.*;
import java.net.Socket;


/**
 * @author tantexian
 * @since 2016/6/24
 */
public class ServerHandle implements Runnable {

    private Socket socket;


    public ServerHandle(Socket socket) {
        this.socket = socket;
    }


    public void run() {
        BufferedReader bufferedReader = null;
        PrintWriter printWriter = null;

        try {
            bufferedReader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            printWriter = new PrintWriter(
                new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream())));
            while (true) {
                String msg = bufferedReader.readLine();
                if (msg == null) {
                    break;
                }
                else {
                    printWriter.println(getAnswer(msg));
                    printWriter.flush();
                }
            }
        }
        catch (IOException e) {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
                if (socket != null) {
                    socket.close();
                }
            }
            catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }



}
